package com.example.demo;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.example.demo.Content.clientId;

/**
 * 自定义WebSocket客户端
 */
@Slf4j
public class CustomizedWebSocketClient extends WebSocketClient {

    //用来接收数据
    private String excptMessage;

    /**
     * 线程安全的Boolean -是否收到消息
     */
    public AtomicBoolean hasMessage = new AtomicBoolean(false);

    /**
     * 线程安全的Boolean -是否已经连接
     */
    private AtomicBoolean hasConnection = new AtomicBoolean(false);

    /**
     * 构造方法
     *
     * @param serverUri
     */
    public CustomizedWebSocketClient(URI serverUri) {
        super(serverUri);
        log.info("CustomizeWebSocketClient init:" + serverUri.toString());
    }

    /**
     * 打开连接是方法
     *
     * @param serverHandshake
     */
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("CustomizeWebSocketClient onOpen");
        //当打开连接时，发送连接信息给服务器完成当前客户端的注册
        this.sendMessage(JSONUtil.toJsonStr(Message.builder().type("connection").data(clientId).build()));
    }

    /**
     * 收到消息时
     *
     * @param s
     */
    @Override
    public void onMessage(String s) {
        log.info("-------------------message :" + s);
        hasMessage.set(true);
        Message message = JSONUtil.parseObj(s).toBean(Message.class);
        switch (message.getType()){
            //接收到连接到服务器时的反馈消息
            case "connection":
                log.info("接收到连接上服务器后服务器返送的消息：" + message.getData());
                excptMessage = message.getData();
                break;
            default:
                log.info("未知消息：" + message.getData());
                break;

        }
    }

    public void sendMessage(String message){
        try{
            this.send(message);
            log.info("已发送消息：" + message);
        }catch ( Exception e){
            log.error("发送消息失败：" + e.getMessage());
        }
    }

    /**
     * 当连接关闭时
     *
     * @param i
     * @param s
     * @param b
     */
    @Override
    public void onClose(int i, String s, boolean b) {
        this.hasConnection.set(false);
        this.hasMessage.set(false);
        log.info("CustomizeWebSocketClient onClose:" + s);
    }

    /**
     * 发生error时
     *
     * @param e
     */
    @Override
    public void onError(Exception e) {
        log.error("CustomizeWebSocketClient onError:" + e);
    }

    @Override
    public void connect() {
        if(!this.hasConnection.get()){
            super.connect();
        }
    }

    //获取接收到的信息
    public String getExcptMessage() {
        if(excptMessage != null){
            String message = new String(excptMessage);
            excptMessage = null;
            return message;
        }
        return null;
    }
}
